package com.qingke.easyjava.springhibernate.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.qingke.easyjava.springhibernate.service.ExpenseService;

public class LoginServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
		ExpenseService service = wac.getBean(ExpenseService.class);

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		if (service.isUserExists(username, password)) {
			request.getSession().setAttribute("username", username);
			request.getSession().setAttribute("logged", new Integer(1));
			response.getWriter().println("<html><script>alert('Login success');window.location.href='index.jsp';</script></html>");
		} else {
			System.out.println("failed");
			response.getWriter().println("<html><script>alert('Login failed');window.history.back()</script></html>");
		}

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
